<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Article;
use App\Http\Model\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    // admin/article   全部文章列表
    public function index()
    {
        $data = Article::orderBy('art_id','desc')->paginate(10);
        return view('admin.article.index',compact('data'));
    }

    //  admin/article/create  添加文章
    public function create()
    {
        $data = (new Category)->tree();
        return view('admin/article/add',compact('data'));
    }

    public function store(Request $request)
    {
        $input = $request->except('_token',"art_thumb_file");
        $input['art_time'] = time();
        $rules = [
            'art_title'=>'required',
            'art_content'=>'required',
            'art_editor'=>'required',
        ];
        $message = [
            'art_title.required'=>'文章标题是必须要填写！',
            'art_content.required'=>'文章内容是必须要填写！',
            'art_editor.required'=>'文章作者是必须要填写！',
        ];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $re = Article::create($input);
            if($re){
                return redirect('admin/article');
            }else{
                return back()->with('errors','数据提交失败，请稍后再试试！');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    //  admin/article/{art_id}/edit 编辑分类
    public function edit($art_id)
    {
        $data = (new Category)->tree();
        $field = Article::find($art_id);
        return view('admin.article.edit',compact('field','data'));
    }

    //  admin/article/{art_id}   更新分类修改数据
    public function update(Request $request,$art_id)
    {
        $input = $request->except('_token','_method','art_thumb_file');
        $re = Article::where('art_id',$art_id)->update($input);
        if($re){
            return redirect('admin/article');
        }else{
            return back()->with('errors',"文章更新失败，请稍后再重试！");
        }
    }

    // delete  admin/article/{art_id}  删除文章
    public function destroy($art_id)
    {
        $re = Article::where('art_id',$art_id)->delete();
        if($re){
            $data = [
                'status'=>0,
                'msg'=>'删除成功！'
            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'删除失败，请稍后再试试！'
            ];
        }
        return $data;
    }

}
